public class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            if (head == null) {//head为空的情况
                return null;
            }
            if (head.next == null) {//head的next为空的情况
                head = null;
                return head;
            }
            ListNode cur = head;
            ListNode prev = head;
            int count = 0;
            while (cur != null) {
                count++;
                cur = cur.next;
            }
            if (count == n) {//要删除的是头结点的情况
                head = prev.next;
                return head;
            }
            for (int i = 0; i < count - n - 1; i++) {//一般情况
                prev = prev.next;
            }
            prev.next = prev.next.next;
            return head;
        }
    }

